package com.doupi.partner.manager.authenticator.filter;

import com.doupi.partner.manager.authenticator.athuc.CaptchaToken;
import com.doupi.partner.service.*;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * web 过滤器创建{@link CaptchaToken CaptchaToken}
 * 
 * @author Alvin Wang
 * @version 1.0.0 on 2017-04-04
 */
public class CaptchaAuthenticationFilter extends BaseAuthenticationFilter {

	private static final String DEFAULT_CAPTCHA_PARAM = "captcha";
	private String captchaParam = DEFAULT_CAPTCHA_PARAM;

	@Autowired
	public CaptchaAuthenticationFilter(AdministratorPermissionService administratorPermissionService, AdministratorHasRoleService administratorHasRoleService,
			AdministratorRoleHasPermissionService administratorRoleHasPermissionService, PartnerRelationService partnerRelationService, AdministratorService administratorService) {
		super(administratorPermissionService, administratorHasRoleService, administratorRoleHasPermissionService, partnerRelationService, administratorService);
	}

	public CaptchaAuthenticationFilter() {
		this(null, null, null, null, null);
	}

	@Override
	protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
		String username = getUsername(request);
		String password = getPassword(request);
		String host = getHost(request);
		boolean rememberMe = isRememberMe(request);
		String captcha = getCaptcha(request);
		return new CaptchaToken(username, password, rememberMe, host, captcha);
	}

	private String getCaptcha(ServletRequest request) {
		return WebUtils.getCleanParam(request, captchaParam);
	}

	public void setCaptchaParam(String captchaParam) {
		this.captchaParam = captchaParam;
	}
}
